package com.talos.framework.common.validation;


import com.talos.framework.common.annotation.Regex;
import com.talos.framework.common.util.collection.EmptyUtils;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.metadata.ConstraintDescriptor;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidator;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;

import java.util.regex.Pattern;

public class RegexValidator implements HibernateConstraintValidator<Regex, String> {

    private String regex;

    @Override
    public void initialize(Regex constraintAnnotation) {
        this.regex = constraintAnnotation.value();
    }

    @Override
    public void initialize(ConstraintDescriptor<Regex> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (EmptyUtils.isEmpty(value)) {
            return true;
        }

        return Pattern.compile(this.regex).matcher(value).matches();
    }

}

